package com.jingdianjichi.subject.application.interceptor;

import com.jingdianjichi.subject.common.context.LoginContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
  *自定义登录拦截器
  */
public class LoginInterceptor implements HandlerInterceptor {

    //获得请求头亲,我们去解析即可,在进入请求前的亲
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String loginId = request.getHeader("loginId");

        if(StringUtils.isNotBlank(loginId)){
            //放入上下文亲
            LoginContextHolder.set("loginId",loginId);      //这时我们最好提供一个工具类和ThreadLocal去做交互亲
            
            //因为我们使用的是ConcurrentHashMap,这个map是不允许你存储null的,所以我们放行一下亲
        }

        
        return true;    //放行亲
    }

    //这个是请求后的,我们要做上下文清除的,否则在次进来的时候会上下文混乱的
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginContextHolder.remove();
    }
}
